package com.my.security.interceptor;

import com.my.security.model.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lbb
 * @fileName SecurityHandlerInterceptor
 * @description 安全认证拦截器
 * @date 2020/5/12 17:22
 */
public class SecurityHandlerInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object object=request.getSession().getAttribute(User.SECURITY_SESSION_USER_KEY);
        if(object==null){
            writeContent(response,"请登录");
            return false;
        }
        User user=(User)object;
        String requestURI=request.getRequestURI();
        //这里access_r1权限唯一标识，r1资源路径
        //这里维护起来会非常麻烦，因此需要引入第三方框架
        if(user.getAuthorities().contains("access_r1")&&requestURI.contains("/r1")){
            return true;
        }
        if(user.getAuthorities().contains("access_r2")&&requestURI.contains("/r2")){
            return true;
        }
        writeContent(response,"没有访问权限");
        return false;
    }

    private void writeContent(HttpServletResponse response,String message)throws IOException{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(message);
        writer.close();
    }
}
